{% extends "shuup/front/macros/theme/basket.jinja" %}
{%- import "shuup/front/macros/order.jinja" as order_macros with context -%}
{%- from "shuup/front/macros/general.jinja" import render_supplier_info -%}

{% macro render_basket_content(basket) %}
    <div class="basket-items">
        <form method="post" action="{{ url("shuup:basket") }}" id="update_basket_form">
            <input name="command" type="hidden" value="update">
            {% csrf_token %}
            {{ render_basket_lines(basket) }}
            {{ render_unorderable_basket_lines(basket) }}
        </form>
        {{ render_used_coupons(basket) }}
        {{ render_coupon_div(basket) }}
        {{ render_basket_summary(basket) }}
    </div>
{% endmacro %}

{% macro _render_basket_line(line) %}
    {% set product = line.product %}
    {% set shop_product = line.shop_product %}
    {% set show_supplier_info = xtheme.get("show_supplier_info") %}
    <div class="single-item">
        {% if product %}
        <div class="product-image">
            {% set image = product.primary_image %}
            {% if not image and product.variation_parent %}
                {% set image = product.variation_parent.primary_image %}
            {% endif %}
            {% if image %}
                <a class="product-name"
                   href="{{ shuup.urls.model_url(product) }}">
                    <img class="img-responsive"
                         src="{{ image|thumbnail(size=(200, 200)) }}"
                         alt="{{ line.text }}">
                </a>
            {% else %}
                <a class="product-name"
                   href="{{ shuup.urls.model_url(product) }}">
                    <img class="img-responsive"
                         src="{{ STATIC_URL }}shuup/front/img/no_image_thumbnail.png">
                </a>
            {% endif %}
        </div>
        {% endif %}
        <div class="product-details">
            <h4 class="name">
                {% if product %}
                    <a class="product-name" href="{{ shuup.urls.model_url(product) }}">{{ line.text }}</a>
                    {% if show_supplier_info %}{{ render_supplier_info(line.supplier) }}{% endif %}
                {% else %}
                    {{ line.text }}
                {% endif %}
            </h4>
            {% if product and product.is_package_parent() %}
                {{ order_macros.render_package_children(product) }}
            {% endif %}
            <div class="quantity">
                {% if product %}
                    {% set unit = shop_product.unit %}
                    {% if line.can_change_quantity %}
                    <div class="input-group">
                        <input
                            id="qty_{{ line.line_id }}"
                            type="number"
                            name="dq_{{ line.line_id }}"
                            size="2"
                            class="line_quantity form-control"
                            step="{{ shop_product.display_quantity_step }}"
                            value="{{ unit.to_display(line.quantity) }}"
                            min="{{ shop_product.display_quantity_minimum }}">
                        <div class="input-group-addon sales-unit">
                            {{ unit.symbol }}
                        </div>
                    </div>
                    {% else %}
                        <div class="">
                            {{ unit.render_quantity(line.quantity, force_symbol=True) }}
                        </div>
                    {% endif %}
                {% endif %}
            </div>
        </div>
        {% if show_prices() and not xtheme.get("hide_prices") %}
            <div class="product-sum">
                <h4 class="price text-right">
                    <small>{% trans %}Total{% endtrans %}: </small>{{ line|price(allow_cache=False) }}
                    {% if line.is_discounted and line.base_price.value > 0 %}
                        <br><small><s class="text-muted">{{ line|base_price(allow_cache=False) }}</s></small>
                    {% endif %}
                </h4>
            </div>
        {% endif %}
        <div class="delete">
            {% if line.can_delete %}
                <button type="submit"
                        class="btn btn-sm"
                        name="delete_{{ line.line_id }}"
                        title="{% trans %}Remove product from basket{% endtrans %}">
                    <i class="fa fa-times"></i>
                </button>
            {% endif %}
        </div>
    </div>
{% endmacro %}

{% macro render_basket_lines(basket) %}
    {% set lines = basket.get_final_lines() %}
    {% if lines %}
        <div class="basket-lines">
            {% for line in lines %}
                {{ _render_basket_line(line) }}
            {% endfor %}
        </div>
    {% endif %}
{% endmacro %}

{% macro render_unorderable_basket_lines(basket) %}
    {% set unorderable_lines = basket.get_unorderable_lines() %}
    {% if unorderable_lines %}
        <div class="basket-unorderable-lines">
            <p class="text-danger">{% trans %}The following items are not currently available (or are not available in the desired quantity) and cannot be included in your order.{% endtrans %}</p>
            {% for line in unorderable_lines %}
                {{ _render_basket_line(line) }}
            {% endfor %}
        </div>
    {% endif %}
{% endmacro %}

{% macro render_basket_summary(basket) %}
    <div class="basket-summary">
        {% if show_prices() and not xtheme.get("hide_prices") %}
            <div class="row">
                <div class="col-xs-12 col-sm-6 pull-right">
                    <div class="row">
                        <div class="total-price-label col-xs-6"><strong>{% trans %}Total{% endtrans %}</strong></div>
                        <div class="total-price text-right col-xs-6"><strong>{{ basket|total_price }}</strong></div>
                    </div>
                </div>
            </div>
        {% endif %}
    </div>
{% endmacro %}

{% macro continue_shopping_button() %}
    <a href="/xtheme/products"
       class="text-muted btn continue-shopping hidden-xs">
        <i class="fa fa-angle-double-left"></i>
        {% trans %}Continue Shopping{% endtrans %}
    </a>
{% endmacro %}

{% macro proceed_to_checkout_button() %}
    <a href="{{ url("shuup:checkout") }}"
       class="btn btn-primary pull-right btn-checkout">
        <i class="fa fa-lock"></i>
        {% trans %}Proceed to checkout{% endtrans %}
        <i class="fa fa-angle-double-right"></i>
    </a>
{% endmacro %}

{% macro render_used_coupons(basket) %}
    {% if basket.codes %}
    <div class="row basket-used-codes">
        <div class="col-sm-6 col-sm-offset-6">
            <p class="used-coupon-text">{% trans %}Coupons applied{% endtrans %}</p>
            {% for code in basket.codes %}
                <div class="basket-used-code">
                    <span class="basket-code">{{ code }}</span>
                    <button class="btn btn-primary basket-remove-code-btn" data-code="{{ code }}" type="button">
                        <i class="fa fa-trash"></i>
                    </button>
                </div>
            {% endfor %}
        </div>
    </div>
    {% endif %}
{% endmacro %}

{% macro render_coupon_div(basket) %}
    <div class="row basket-discount-code">
        <div class="col-sm-6 pull-right">
            <p class="coupon-text">{% trans %}Do you have a coupon code? Enter it here. {% endtrans %}</p>
            <div id="collapseCoupon">
                <div class="input-group">
                    <input type="text"
                        class="form-control"
                        name="code"
                        id="discount-code"
                        placeholder="{% trans %}Coupon Code{% endtrans %}">
                    <span class="input-group-btn">
                        <button type="submit"
                                id="submit-code"
                                class="btn btn-primary">
                            {% trans %}Submit Code{% endtrans %}
                        </button>
                    </span>
                </div>
            </div>
            <hr>
        </div>
    </div>
{% endmacro %}

{% macro render_cart_saver() %}
    {% if request.person and shuup.urls.has_url("shuup:saved_cart.save") %}
        <div class="cart-saver row">
            <div class="col-sm-6 col-sm-offset-6">
                <div class="clearfix">
                    <a class="btn btn-primary cart-saver-toggle pull-right btn-save-cart"
                       href="#collapseSaveCart"
                       data-toggle="collapse">
                        {% trans %}Save cart{% endtrans %}
                    </a>
                </div>
                <div class="collapse" id="collapseSaveCart">
                    <div class="input-group input-save-cart">
                        <input type="text"
                               id="cart-title"
                               class="form-control"
                               name="title"
                               placeholder="{% trans %}Cart Title{% endtrans %}">
                        <span class="input-group-btn">
                            <button id="save-cart"
                                    type="submit"
                                    class="btn btn-primary">
                                {% trans %}Save{% endtrans %}
                            </button>
                        </span>
                    </div>
                    <div id="save-cart-status" class="pull-right"></div>
                </div>
            </div>
        </div>
    {% endif %}
{% endmacro %}

{% macro render_empty_basket_actions() %}
    <a href="/xtheme/products" class="btn btn-primary">
        <i class="fa fa-angle-double-left"></i>
        {% trans %}Back to Products{% endtrans %}
    </a>
{% endmacro %}

{% macro render_extrajs() %}
    <script type="text/javascript">
        $(function() {
            {{ update_quantity_js() }}
            {{ submit_coupon_code() }}
            {{ save_cart_js() }}
            {{ single_submit_form() }}
            {{ remove_basket_code() }}
        });
    </script>
{% endmacro %}

{% macro update_quantity_js() %}
    function checkEvent(e) {
        return (e.which == 13 || e.keyCode == 13 || e.key == "Enter");
    }

    $("#update_basket_form .quantity :input")
    .keydown(function(e) {
        if (checkEvent(e)) {
            e.preventDefault();
        }
    })
    .keyup(function(e) {
        if (checkEvent(e)) {
            $("#update_basket_form").submit();
        }
    })
    .change(function() {
        $("#update_basket_form").submit();
    });
{% endmacro %}

{% macro remove_basket_code() %}
    $(".basket-remove-code-btn").click(function(evt) {
        var code = $(evt.currentTarget).data("code");
        if (code) {
            var data = {
                "command": "remove_campaign_code",
                "code": code
            };
            $.ajax({
                url: "",
                method: "POST",
                data: data,
                success: function(response) {
                    if (response.ok) {
                        location.reload();
                    } else {
                        alert("{% trans %}Error!{% endtrans %} {% trans %}Invalid coupon code.{% endtrans %}")
                    }
                },
                error: function() {
                    alert("{% trans %}Error!{% endtrans %} {% trans %}Removing a coupon failed.{% endtrans %}")
                }
            });
        }
    });
{% endmacro %}

{% macro submit_coupon_code() %}
    $("#submit-code").click(function(e){
        e.preventDefault();
        var coupon = $("#discount-code").val();

        if (coupon.length) {
            // ajax request to command
            var data = {
                "command": "add_campaign_code",
                "code": coupon
            };

            $.ajax({
                url: "",
                method: "POST",
                data: data,
                success: function(response) {
                    if (response.ok) {
                        location.reload();
                    } else {
                        alert("{% trans %}Error!{% endtrans %} {% trans %}Coupon is not available.{% endtrans %}")
                    }
                },
                error: function() {
                    alert("{% trans %}Error!{% endtrans %} {% trans %}Adding a coupon failed.{% endtrans %}")
                }
            });
        }
    });
{% endmacro %}

{% macro save_cart_js() %}
    {% if shuup.urls.has_url("shuup:saved_cart.save") %}
        $("#save-cart").click(function(e){
            e.preventDefault();
            var title = $("#cart-title").val();
            $("#save-cart-status").empty();
            $.ajax({
                url: "{{ url('shuup:saved_cart.save') }}",
                method: "POST",
                data: {
                    title: title,
                    csrfmiddlewaretoken: "{{ csrf_token }}"
                },
                success: function(response) {
                    $("#save-cart-status").append("<p>" + "{% trans %}Success!{% endtrans %} {% trans %}Cart saved.{% endtrans %}" + "</p>");
                },
                error: function(e) {
                    $("#save-cart-status").append("<p>" + "{% trans %}Error!{% endtrans %}" + e.responseJSON.error + "</p>");
                }
            });
        });
    {% endif %}
{% endmacro %}

{% macro single_submit_form() %}
    window.singleSubmitForm = function($form) {
        var canSubmit = true;
        $form.submit(function() {
            if(canSubmit) {
                canSubmit = false;
            }
            else {
                return false;
            }
        });
    };
    singleSubmitForm($("#update_basket_form"));
{% endmacro %}
